/** 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package it.free.i.virtual.machine;

import it.free.i.naming.CachedNamingProviderProxy;
import it.free.i.virtual.machine.hal.LinkingOperationException;

import javax.naming.NamingException;

import org.apache.log4j.Logger;

/**  
 * ISystem default provided virtual machine
 * @author stefano
 */
public class VirtualMachineDefaultImpl implements VirtualMachine {

	private static Logger logger = null;
	
	static{
		logger = Logger.getLogger(VirtualMachineDefaultImpl.class);
	}
	
	public VirtualMachineDefaultImpl() {
	}

	/**
	 * @see it.free.i.virtual.machine.VirtualMachine
	 */
	public void start(String jndiConfigurationFilePath)throws VirtualMachineGeneralException {
		
		logger.info("ISystem starting");
		
		try{
			logger.info("Initializing naming service provider proxy with naming provider: [" + jndiConfigurationFilePath + "]");
			CachedNamingProviderProxy.getInstance().setup(jndiConfigurationFilePath);
			//This will cause an exception if server is not reachable
			CachedNamingProviderProxy.getInstance().checkNamingServer();
			
			//Visitor pattern to activate system components
			//Enumeration<String> subsystemNames = BootStrapAbleObjectsInventory.getInstance().
			//Iterator<BootstrapAble> subsystemsIterator = BootStrapAbleObjectsInventory.getInstance().iterator();
			String subsystemToActivateName = null;
			BootstrapAble subsystem = null;
			logger.info("Bootstrapping system components");
			for(int i=0; i < BootStrapAbleObjectsInventory.getInstance().size(); i++){
				subsystem = BootStrapAbleObjectsInventory.getInstance().get(i);
				subsystemToActivateName = subsystem.getClass().getSimpleName();
				logger.info("Activating subsystem [" + subsystemToActivateName + "]");
				subsystem.boot();
				logger.info("Subsystem [" + subsystemToActivateName + "] activated succesfully");
			}
			
		}catch(NamingException nExc) {
			   logger.error("Unable to initialize naming provider prox:", nExc);
			   System.exit(-1);
		}catch(LinkingOperationException isdaloExc){
			   logger.error("Unable to initialize at least one subsystem:", isdaloExc);
			   System.exit(-1);
		}
		
	}

}
